<?php
namespace Modules\Order\Entities;

use Illuminate\Support\Facades\DB;
use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;
use Setting;

use Asset;

class OrderSku extends Model
{
    protected $guarded = [];
    protected $table = 'order_skus';

    protected $casts = [
        'sku_assets' => 'json',
        'attrs' => 'json',
        'options' => 'json'
    ];

    protected $appends = ['node_type_text'];

    static public $resourceName = '订单sku';

    // public $activity = NULL;
    public $optionsTemp = [];
    public $skuable = NULL;
    public $base_sku = false;

    public function order()
    {
        return $this->belongsTo('\Modules\Order\Entities\BaseOrder', 'order_id');
    }

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    // 获取基础sku
    public function base_sku()
    {
        $map = config('map.base_sku_type');

//         \Log::error($map);

        $class = @$map[$this->base_sku_type];

        return $this->belongsTo($class, 'sku_id');
    }

    // 获取基础sku
    public function base_sku_()
    {
        $map = config('map.base_sku_type');

//         \Log::error($map);

        $class = @$map[$this->base_sku_type];

        return $this->belongsTo($class, 'sku_id');
    }

    // 已支付的
    public function scopePaid($query)
    {
        return $query->whereHas('order', function ($q) {
            return $q->paid();
        });
    }

    // 属于某用户的订单
    public function scopeForUser($query, $user)
    {
        return $query->whereHas('order', function ($q) use ($user) {
            return $q->where('user_id', $user->id);
        });
    }

    // 已支付的
    public function scopeReturnSaled($query)
    {
        return $query->whereHas('order', function ($q) {
            return $q->where('status', 8);
        });
    }

    // 订单类型
    public function scopeOrderType($query, $type)
    {
        return $query->whereHas('order', function ($q) use ($type) {
            return $q->type($type);
        });
    }

    // 计算人民币价格
    public function calcMoneyPrice()
    {
        return $this->skuable->getSellingPrice('money', $this->optionsTemp) * $this->total;
    }

    // 计算积分价格
    public function calcScorePrice()
    {
        return $this->skuable->getSellingPrice('score', $this->optionsTemp) * $this->total;
    }

    // 生成attr属性
    public function generateAttrStr()
    {
        $attrs = $this->attrs ?: [];

        $str = '';
        foreach ($attrs as $item) {
            $str .= (@$item['k'] ?: @$item['key']) . ':' . (@$item['v'] ?: @$item['value']) . '   ';
        }

        return $str;
    }

    // 扣减库存
    public function addSales() 
    {
    	if ($this->base_sku) {
	        // 部分sku不用扣减库存
	        if ($this->base_sku->skipReduceStock) {
	            return true;
	        }

	        // 扣sku库存
	        // \Log::error($this->base_sku->title);
	        if (!$this->base_sku->addSales($this->total)) {
	            return false;
	        }
    	}

    	if ( in_array($this->node_type, ['fudai', 'leitai', 'choushang']) ){
            DB::update("update ".$this->node_type.'_activity'." set stock = stock - {$this->total}, sales = sales + {$this->total} where id = {$this->node_id} ");
        }


        // 秒杀活动扣库存 
        if ($this->activity_type === 'seckill') {
            $activity = $this->activity;
            // 扣活动库存
            if ($activity) {
                if (!$activity->addSales($this->total)) {
                    return false;
                }
            }
        }

        return true;
    }

    // 订单退款返回库存
    public function reduceSales() 
    {
    	if ($this->base_sku) {
	        // 部分sku不用扣减库存
	        if ($this->base_sku->skipReduceStock) {
	            return true;
	        }
	        
	        // 增加库存
	        $this->base_sku->reduceSales($this->total);
    	}

        if ( in_array($this->node_type, ['fudai', 'leitai', 'choushang']) ){
            DB::update("update ".$this->node_type.'_activity'." set stock = stock + {$this->total}, sales = sales - {$this->total} where id = {$this->node_id} ");
        }

        // $activity = $this->activity()->first();

        // 秒杀活动扣库存 
        if ($this->activity_type === 'seckill') {
            $activity = $this->getActivity();
            // 扣活动库存
            if ($activity) {
                $activity->reduceSales($this->total);
            }
        }
    }

    // 发放商品下单奖励(如果有的话)
    public function sendProductReward()
    {
        $user = $this->user;

        if ($this->reward_assets) {
            $reward = Asset::sendTo($this->reward_assets, $user, [
                'description' => '下单赠送',
                'type' =>  'order_reward'
            ]);
        }
    }

    static public function initWith($skuable, $total, $options = [])
    {
        $info = [];

        $activity = @$options['activity'];  // 活动价
        // $node = @$options['']
        $groupPrice = @$options['group_price'];  // 人群价

        // \Log::error($activity);
        // \Log::error($groupPrice);

        // 此sku实现有generateSkuInfo则直接调用该接口， 否则一个个生成信息
        if (method_exists($skuable, 'generateSkuInfo')) {
            $info = $skuable->generateSkuInfo();
        }else {
            $isHiddenSku = method_exists($skuable, 'isHiddenSku') ? $skuable->isHiddenSku() : 0;

            $node = $skuable->getNodeEntity();

            $info = [
                'sku_id' => $skuable->id,
                'sku_uuid' => $skuable->uuid,
                'base_sku_type' => $skuable->getType('base_sku_type'),
                'activity_id' => @$activity->id,
                'activity_uuid' => @$activity->uuid,
                'activity_type' => @$activity->activity_type,
                'node_id' => @$node->id,
                'node_uuid' => @$node->uuid,
                'node_type' => $skuable->getType('node_type'),
                'sku_type' => $skuable->sku_type ?: 1,
                'is_hidden_sku' => $isHiddenSku,
                'title' => $skuable->title,
                'thumb' => $skuable->thumb,
                'number' => $skuable->number,
                'supplier' => $skuable->getSupplier(),
                'cost_money_price' => $skuable->cost_money_price,
                'group_price_title' => @$groupPrice->title,
                'attrs' => $skuable->getAttrs(),
                'money_price' => $skuable->getOriginalPrice('money'),
                'discount_money_price' => $skuable->getSellingPrice('money', $options),
                'score_price' => $skuable->getOriginalPrice('score'),
                'discount_score_price' => $skuable->getSellingPrice('score', $options),
                'pay_order_id' => $skuable->pay_order_id,
                'pay_order_number' => $skuable->pay_order_number,
                'brokerage_money' => $skuable->getBrokerage('money', $total),
                'brokerage_score' => $skuable->getBrokerage('score', $total),
                'reward_assets' => $skuable->getRewardAssets($total),
                'sku_assets' => $skuable->getOrderAssets(),
            ];

            // \Log::error($info);
        }

        $info['uuid'] = uniqid();
        $info['total'] = $total;

        $orderSku = new OrderSku($info);

        $orderSku->skuable = $skuable;
        $orderSku->optionsTemp = @$options;

        return $orderSku;
    }

    public function calcReturnSaleInfo()
    {
        $sku = $this;
        $baseSku = $sku->base_sku;
        $returnScore = 0;
        $returnMoney = 0;
        $returnRedpack = 0;

        // 折价率
        $returnRatio = Setting::returnSaleRatio();

        // 计算返售原价 (积分 + 人民币)
        if ($baseSku && ($baseSku->score_price || $baseSku->money_price)) {
            // 有设置返售原价
            $baseScore = $baseSku->score_price;
            $baseMoney = $baseSku->money_price;
        }
        else {
            // 未设置返售原价
            $baseScore = $sku->discount_score_pric;
            $baseMoney = $sku->discount_money_price;
        }

        // 计算返售应获得的积分和人民币
        $returnScore = floor($baseScore * $returnRatio);
        $returnMoney = floor($baseMoney * $returnRatio);
        

        $moneyReturnType = Setting::returnSaleTypeForMoney();
        if ($moneyReturnType === 'money') {
            // 原路退回
        }
        elseif ($moneyReturnType === 'redpack') {
            $returnRedpack = $returnMoney;
            $returnMoney = 0;
        }
        elseif ($moneyReturnType === 'score') {
            // 人民币兑积分比率, 每1元兑换的积分数量
            $ratio = Setting::returnMoneyToScoreRatio();
            $returnScore += floor($returnMoney / 100 * $ratio);
            $returnMoney = 0;
        }

        // 打补丁，如果原路退回的金额超出订单支付金额，需要把超出的部分强制退回到红包余额
        if ($returnMoney > $sku->discount_money_price) {
            $diff = $returnMoney - $sku->discount_money_price;
            $returnMoney -= $diff;
            $returnRedpack += $diff;
        }

        return [
            $returnMoney,
            $returnRedpack,
            $returnScore
        ];
    }
}
